package com.weir.r2dbc.webclient.demo;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/test")
public class TestController {

	@GetMapping("/slow-service-tweets")
	private List<Tweet> getAllTweets() {
		try {
			Thread.sleep(2000L);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // delay
		return Arrays.asList(new Tweet("RestTemplate rules", "@user1"), new Tweet("WebClient is better", "@user2"),
				new Tweet("OK, both are useful", "@user1"));
	}

	@ResponseBody
	@GetMapping("/tweets-blocking")
	public List<Tweet> getTweetsBlocking() {
		System.out.println("Starting BLOCKING Controller!");
		final String uri = "http://127.0.0.1:8080/test/slow-service-tweets";
		RestTemplate restTemplate = new RestTemplate();

		ResponseEntity<List<Tweet>> response = restTemplate.exchange(uri, HttpMethod.GET, null,
				new ParameterizedTypeReference<List<Tweet>>() {
				});

		List<Tweet> result = response.getBody();
		System.out.println(result);
		System.out.println("Exiting BLOCKING Controller!");
		return result;
	}

	@ResponseBody
	@GetMapping(value = "/tweets-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	public Flux<Tweet> getTweetsNonBlocking() {
		Tweet tw = new Tweet();
		System.out.println("Starting NON-BLOCKING Controller!");
		Flux<Tweet> tweetFlux = WebClient.create().get().uri("http://127.0.0.1:8080/test/slow-service-tweets")
				.retrieve().bodyToFlux(Tweet.class);

		tweetFlux.subscribe(tweet -> System.out.println(tweet.toString()));
		System.out.println("Exiting NON-BLOCKING Controller!");
		return tweetFlux;
	}

}
